package cn.lcfms.cms.collect;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.ListIterator;

import org.apache.commons.io.FileUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import cn.lcfms.bin.core.Application;
import cn.lcfms.cms.CollctBase;
import cn.lcfms.cms.Collect;
import cn.lcfms.cms.CollectResult;

public class Test extends CollectResult{
	
	private static String[] alt= {"女","性感","清纯"};

	public Test(Collect collect) {
		super(collect);
	}
	
	public static boolean checkInArray(String str) {
		for(int i=0;i<alt.length;i++) {
			if(str.indexOf(alt[i])!=-1) {
				return true;
			}
		}
		return false;
	}

	@Override
	public boolean _do(HashMap<String, String> content) {	
		String body=content.get("content");
		getTImg(body);
		return true;
	}
	
	private void getTImg(String content) {
		Document doc = Jsoup.parse(content);
		Elements a = doc.select("img[src]");
		ListIterator<Element> iterator = a.listIterator();
		try {
			URL _url = new URL(collect.getNowUrl());
			String path=_url.getProtocol()+"://"+_url.getHost()+_url.getFile();
			path=path.substring(0, path.lastIndexOf("/"))+"/";
			String host=_url.getProtocol()+"://"+_url.getHost()+"/";
			while (iterator.hasNext()) {
				Element next = iterator.next();
				String attr = next.attr("src");
				String alt = next.attr("alt");
				
				if(!checkInArray(alt)) {
					continue;
				}				
				if(attr.startsWith("/")) {
					attr=host+attr.substring(1);
				}
				if(attr.startsWith("./")) {			
					attr=path+attr.substring(2);
				}
				if(!attr.startsWith("http")) {
					attr=path+attr;
				}	
				try {
					
					byte[] browser = CollctBase.browser(attr, collect.getBean().getCookie());
					String shortfile = CollctBase.getFileName(attr);
					String filepath=Application.ROOT_PATH+"uploadfile"+Application.F+"images"+Application.F+"meinv"+Application.F+shortfile;
					File file=new File(filepath);
					if(!file.exists()) {
						FileUtils.writeByteArrayToFile(file, browser);
					}			
				} catch (IOException e) {
					continue;
				}
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}		
	}
}
